package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.database.entity.ConstellationGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 十二宫工作
class ConstellationWork(
    private val config: ConstellationGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "十二宫"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 从config中获取关卡ID
            val sceneId = config.getSceneId()
            if (sceneId == null) {
                historyManager.addHistory(name, "关卡解析失败，当前配置为${config.levelName}")
                return WorkResult.Failure(Exception("关卡解析失败"), "关卡解析失败")
            }
            
            // 2. 先查询十二宫信息，检查剩余次数
            val queryResult = gameApi.queryConstellation()
            queryResult.fold(
                onSuccess = { response ->
                    // 3. 检查剩余次数
                    if (response.leftChallengeTimes > 0) {
                        // 4. 自动扫荡指定的十二宫
                        val fightResult = gameApi.fightConstellation(sceneId)
                        fightResult.fold(
                            onSuccess = { fightResponse ->
                                historyManager.addHistory(name, fightResponse.getDescription())
                                WorkResult.Success
                            },
                            onFailure = { exception ->
                                historyManager.addHistory(name, exception.message)
                                WorkResult.Failure(exception, exception.message)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                    WorkResult.Failure(exception, exception.message)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}